<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="所属模块" prop="strModular">
        <treeselect style="width: 300px;" v-model="queryParams.strModular" :show-count="true"
                    :multiple="true"
                    :disable-branch-nodes="true"
                    @keyup.enter.native="handleQuery"
                    :options="modularTree"  placeholder="请输入所属模块" />
      </el-form-item>
      <el-form-item label="所属报表" prop="strReport">
        <treeselect style="width: 300px;" v-model="queryParams.strReport" :show-count="true"
                    :multiple="true"
                    :disable-branch-nodes="true"
                    @keyup.enter.native="handleQuery"
                    :options="reportTree"  placeholder="请输入所属报表" />
      </el-form-item>
      <el-form-item label="所属客户" prop="strCustomer">
        <treeselect style="width: 300px;" v-model="queryParams.strCustomer" :show-count="true"
                    :multiple="true"
                    :disable-branch-nodes="true"
                    @keyup.enter.native="handleQuery"
                    :options="customerTree"  placeholder="请输入所属客户" />
      </el-form-item>
      <el-form-item label="添加人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入添加人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="语句内容" prop="sqlScript">
        <el-input
          v-model="queryParams.sqlScript"
          placeholder="请输入表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="需求BUG编号" prop="demandBugId" v-show="showSearchColl">
        <el-select filterable clearable v-model="queryParams.demandBugId" style="width: 300px" placeholder="请选择需求BUG编号">
          <el-option
            v-for="demandBugInfo in demandBugInfoList"
            :key="demandBugInfo.id"
            :label="`${demandBugInfo.demandBugNum}【${demandBugInfo.description.slice(0,50)}】`"
            :value="demandBugInfo.id"
            @keyup.enter.native="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据库类型" prop="dataBaseType" v-show="showSearchColl">
        <el-select v-model="queryParams.dataBaseType" placeholder="请选择数据库类型" clearable>
          <el-option
            v-for="dict in dict.type.report_database_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否同时存在" prop="coverPrimaryKey" v-show="showSearchColl">
        <el-select v-model="queryParams.coverPrimaryKey" placeholder="请选择是否同时存在" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="版本号" prop="version" v-show="showSearchColl">
        <el-select v-model="queryParams.version" placeholder="请选择版本号" clearable>
          <el-option
            v-for="dict in dict.type.report_version"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" v-show="showSearchColl">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status" v-show="showSearchColl">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_common_status_all"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['reportworld:script:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['reportworld:script:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['reportworld:script:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multipleProcess"
          @click="processSqlScript"
          v-hasPermi="['reportworld:script:process']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multipleRebut"
          @click="rebutSqlScript"
          v-hasPermi="['reportworld:script:rebut']"
        >退回</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="reductionData"
          v-hasPermi="['reportworld:reductionData']"
        >还原</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['reportworld:script:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportSql"
          v-hasPermi="['reportworld:script:exportSql']"
        >导出SQL</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" :showSearchColl.sync="showSearchColl" :searchColl="searchColl" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border="border" max-height="550px" v-loading="loading" :data="scriptList"
              @selection-change="handleSelectionChange"
              @sort-change="handleSortChange" :row-style="tableRowStyle"
              @row-click="rowClick"  ref="script">
      <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-hasPermi="['reportworld:script:query','reportworld:script:edit','reportworld:script:remove',
        'reportworld:script:process','reportworld:script:rebut']"
          label="操作" align="center" width="230" class-name="small-padding fixed-width">
            <template   slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleUpdate(scope.row,false)"
                v-hasPermi="['reportworld:script:query']"
              >详情</el-button>
                <el-button v-if="scope.row.isShowUpdate === 1 && (scope.row.status === 3 || scope.row.status === 5 )"
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['reportworld:script:edit']"
                >修改</el-button>
                <el-button v-if="scope.row.isShowUpdate === 1 && scope.row.status === 3"
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['reportworld:script:remove']"
                >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleViewLogger(scope.row)"
                v-hasPermi="['reportworld:script:query:logger']"
              >检查日志</el-button>
              <el-button v-if="scope.row.status === 3"
                size="mini"
                type="text"
                icon="el-icon-check"
                @click="processSqlScript(scope.row)"
                v-hasPermi="['reportworld:script:process']"
              >审核</el-button>
              <el-button v-if="scope.row.status === 3"
                size="mini"
                type="text"
                icon="el-icon-circle-close"
                @click="rebutSqlScript(scope.row)"
                v-hasPermi="['reportworld:script:rebut']"
              >退回</el-button>
             <!-- <el-dropdown v-if="scope.row.status === 3" size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['reportworld:script:process', 'reportworld:script:rebut']">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="scope.row.status === 3" command="processSqlScript" icon="el-icon-check"
                                    v-hasPermi="['reportworld:script:process']">审核</el-dropdown-item>

                 <el-dropdown-item v-if="scope.row.status === 3" command="rebutSqlScript" icon="el-icon-circle-close"
                                  v-hasPermi="['reportworld:script:rebut']">退回</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>-->
            </template>
        </el-table-column>
      <el-table-column label="SQL脚本" align="center" prop="sqlScript" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="所属模块" align="center" prop="modularName" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="所属报表" align="center" prop="reportName" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="所属客户" align="center" prop="customerName" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="报表世界所在分层" align="center" prop="layered" width="180"
                       :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.report_table_layered" :value="scope.row.layered"/>
        </template>
      </el-table-column>
      <el-table-column label="需求BUG编号" align="center" prop="demandBugNum" width="180" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="SQL类型" align="center" prop="ftype" width="180" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="来源" align="center" prop="fsource" width="180" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="数据库类型" width="180" align="center" prop="dataBaseType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.report_database_type" :value="scope.row.dataBaseType"/>
        </template>
      </el-table-column>
      <el-table-column label="是否同时存在" width="180" align="center" prop="coverPrimaryKey">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.coverPrimaryKey"/>
        </template>
      </el-table-column>
      <el-table-column label=" 是否更新数据标记" width="180" align="center" prop="dataMark">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.dataMark"/>
        </template>
      </el-table-column>
      <el-table-column label="版本号" width="180" align="center" prop="version">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.report_version" :value="scope.row.version"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="180" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status_all" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" width="150" prop="createBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="编辑时间" align="center" prop="updateTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑人" align="center" width="150" prop="updateBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="审核人" align="center" width="150" prop="approvalBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="审核时间" align="center" prop="approvalTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退回原因" width="200" align="center" prop="approvalReason" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改SQL脚本管理对话框 -->
    <el-dialog v-if="open" :before-close="cancel" :title="title" :close-on-click-modal ="false" :visible.sync="open" width="1300px" append-to-body >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="form.status === 5 && form.approvalReason" label="退回原因" prop="approvalReason">
              <el-input maxlength="200" v-model="form.approvalReason" type="textarea" />
            </el-form-item>
          </el-col>

          <el-col :span="followUpVersionShow == true?'12':'24'">
            <el-form-item label="版本号" prop="version">
              <el-select :disabled="false" @change="changeVersion($event)" clearable v-model="form.version" placeholder="请选择版本号">
                <el-option
                  v-for="dict in versions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"  v-if="followUpVersionShow">
            <el-form-item  label="更新后续版本" prop="followUpVersion">
              <el-radio-group v-model="form.followUpVersion">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
              <span slot="label">
                <el-tooltip content="提交的脚本不是最新版本的数据，需要同步更新后面的所有版本选择是，反正选择否" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                更新后续版本
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属模块" prop="modularId">
              <treeselect  v-model="form.modularId"
                           @select="selectModular"
                           :beforeClearAll="clearSlect"
                           :disabled="disModular"
                           :show-count="true"
                           :multiple="false"
                           :disable-branch-nodes="true"
                           :options="modularTree"
                           placeholder="请选择所属模块"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属客户" prop="customerId">
              <treeselect  v-model="form.customerId"
                           :show-count="true"
                           @select="selectCustomer"
                           :beforeClearAll="clearSlect"
                           :disabled="disCustomer"
                           :multiple="false"
                           :disable-branch-nodes="true"
                           :options="customerTree"
                           placeholder="请选择所属客户"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属报表" prop="reportId">
              <treeselect  v-model="form.reportId"
                           :show-count="true"
                           @select="selectReport"
                           :beforeClearAll="clearSlect"
                           :disabled="disReport"
                           :multiple="false"
                           :disable-branch-nodes="true"
                           :options="reportTree"
                           placeholder="请选择所属报表"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求BUG编号" prop="demandBugId">
              <el-select filterable clearable  @change="changeDemandBugInfo($event)" v-model="form.demandBugId" style="width: 90%" placeholder="请选择需求BUG编号">
                <el-option
                  v-for="demandBugInfo in demandBugInfoList"
                  :key="demandBugInfo.id"
                  :label="`${demandBugInfo.demandBugNum}【${demandBugInfo.description.slice(0,50)}】`"
                  :value="demandBugInfo.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="SQL脚本" prop="sqlScript">
              <monaco-editor ref="monacoEditor"
                             @changeValue="changeValue($event)"
                             style="border:1px solid #000;"
                             :opts="opts"></monaco-editor>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input maxlength="500" clearable v-model="form.remark" type="textarea" placeholder="请输入内容"/>
              <span slot="label">
                <el-tooltip content="描述信息填写提交得脚本是修复什么问题，影响什么功能等信息" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                描述
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否同时存在" prop="coverPrimaryKey">
              <el-radio-group  v-model="form.coverPrimaryKey" :disabled="coverPrimaryKeyDis">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
              <span slot="label">
                <el-tooltip content="某些个性化的数据，例如客户个性化的配置，公用也存在的时候，需要选择同时存在。公用和个性化得后续更新也需要选择是" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                是否同时存在
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新数据标记" prop="dataMark">
              <el-radio-group v-model="form.dataMark">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
              <span slot="label">
                <el-tooltip content="数据标记的所属报表，所属模块，所属客户不正确的情况，选择是会更新重新覆盖数据对应的标记，注意：调整字段的时候，对应的表也会更新" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                更新数据标记
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item  label="所在分层"  prop="layered">
              <el-select filterable clearable v-model="form.layered" placeholder="报表世界所在分层">
                <el-option
                  v-for="dict in dict.type.report_table_layered"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
              <span slot="label">
                <el-tooltip content="用于区分表所在的分层信息，提交的脚本如果没有建表语句，系统没有提示不需要选择（DWD为数据明细层，DWS为标准层，ADS为数据集市层，DWM为中间层）" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                所在分层
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库类型" prop="dataBaseType">
              <el-select filterable clearable v-model="form.dataBaseType" placeholder="请选择数据库类型">
                <el-option
                  v-for="dict in dict.type.report_database_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
              <span slot="label">
                <el-tooltip content="用于区很某些字段在库里插入的是一个SQL语句的情况，例如报表数据集的表。系统没有提示不需要选择" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                数据库类型
              </span>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item v-if="false" label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isUpdate" type="primary" :loading="butloading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- SQL检查和执行结果 -->
    <el-dialog  :title="titleMsg"  :visible.sync="openMsg" :close-on-click-modal ="false" width="1300px" height="500px" append-to-body>
        <el-col :span="24" style="height:500px">
          <!-- <textarea  v-model="msg" style="width:100%;height: 492px" contentEditable="true">
             <span contenteditable="false">解析SQL出现错误：</span><span style="color: red">500</span>
           </textarea>-->

          <div style="border: 1px solid #CBCBCB;height: 480px;width: 1270px;overflow-x:auto">
            <span style="white-space: pre-wrap;font-size: 12px" v-html="msg"></span>
          </div>
        </el-col>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="subScriptSql" type="primary" :loading="butloading" @click="submitSubScriptSql">确 定</el-button>
        <el-button @click="openMsg = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 版本还原选择版本号 -->
    <el-dialog v-if="openReduction"  :title="titleReduction" :close-on-click-modal ="false" :visible.sync="openReduction" width="500px" height="100px" append-to-body>
      <el-form ref="formReduction" :model="formReduction" :rules="rulesReduction"  label-width="100px">
        <el-row>
          <el-col :span="24" style="height:100px ">
            <el-form-item label="还原版本号" prop="reductionVersion">
              <el-select clearable v-model="formReduction.reductionVersion"
                         placeholder="请选择版本号">
                <el-option
                  v-for="dict in reductionVersions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReduction">确 定</el-button>
        <el-button @click="openReduction = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改需求bug信息对话框 -->
    <el-dialog v-if="openDemandbug"  :title="titleDemandbug" :close-on-click-modal ="false" :visible.sync="openDemandbug" width="800px" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="需求BUG编号" prop="demandBugNum">
              <el-input clearable maxlength="30" v-model="form2.demandBugNum" placeholder="请输入需求/者bug编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求/BUG" prop="demandBugType">
              <el-radio-group v-model="form2.demandBugType">
                <el-radio
                  v-for="demandBugType in demandBugTypes"
                  :key="demandBugType.value"
                  :label="parseInt(demandBugType.value)"
                >{{demandBugType.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外部/内部" prop="demandBugFsource">
              <el-radio-group v-model="form2.demandBugFsource">
                <el-radio
                  v-for="demandBugFsource in demandBugFsources"
                  :key="demandBugFsource.value"
                  :label="parseInt(demandBugFsource.value)"
                >{{demandBugFsource.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求BUG日期" prop="demandBugDate">
              <el-date-picker clearable
                              v-model="form2.demandBugDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择需求BUG日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="需求内容" prop="description">
              <el-input maxlength="500" clearable v-model="form2.description" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-select :disabled="true" clearable v-model="form2.version" placeholder="请选择版本号">
                <el-option
                  v-for="dict in dict.type.report_version"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form2.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input maxlength="500" clearable v-model="form2.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="butloading" @click="submitForm2">确 定</el-button>
        <el-button  @click="openDemandbug = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listScript, getScript, delScript, addScript, updateScript,init,checkSqlScript,processSqlScript,rebutSqlScript ,reductionData} from "@/api/reportworld/script";
import { getTableRowStyle } from "@/utils/yss";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import monacoEditor from '@/components/SqlEditor';
import demandbug from "@/views/reportworld/demandbuginfo/index";
import { addInfo} from "@/api/reportworld/demandbuginfo";

export default {
  name: "Script",
  components: {
    monacoEditor,
    Treeselect,
    demandbug
  },
  dicts: ['report_database_type', 'sys_yes_no', 'report_version','sys_common_status','sys_common_status_all','report_table_layered'],
  data() {
    const equalToSqlScript = (rule, value, callback) => {
      if (this.$refs.monacoEditor.getVal()) {
        callback()
      } else {
        callback(new Error("SQL脚本不能为空"));
      }
    };
    return {
      // 数据范围选项
      demandBugTypes: [
        {
          value: 1,
          label: "需求"
        },
        {
          value: 2,
          label: "BUG"
        }
      ],
      demandBugFsources: [
        {
          value: 1,
          label: "外部"
        },
        {
          value: 2,
          label: "内部"
        }
      ],
      butloading:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数据的状态
      checkstatus:[],
      isShowUpdates :[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //审核和退回按钮禁用
      multipleProcess: true,
      multipleRebut: true,
      subScriptSql:false,
      isUpdate :false,
      // 显示搜索条件
      showSearch: true,
      searchColl:true,
      showSearchColl:false,
      // 总条数
      total: 0,
      // SQL脚本管理表格数据
      scriptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openMsg:false,
      titleMsg: "",
      msg:"",
      // 还原弹出框
      titleReduction: "",
      openReduction:false,
      reductionVersions:[],
      versions:[],
      idList:[],
      //所属模块
      modularTree : [],
      // 所属客户
      customerTree: [],
      //所属报表
      reportTree: [],
      // 需求BUG
      demandBugInfoList:[],
      disModular:false,
      disCustomer:false,
      disReport:false,
      isSql:false,
      followUpVersionShow:false,
      // 日期范围
      dateRange: [],
      titleDemandbug:'',
      openDemandbug:false,
      coverPrimaryKeyDis:true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        sqlScript: null,
        customerId: null,
        reportId: null,
        modularId: null,
        demandBugId: null,
        layered: null,
        fsource: null,
        dataBaseType: null,
        coverPrimaryKey: null,
        version: null,
        hisVersion:null,
      } ,
      opts: { //编辑器
        value: '',
        readOnly: false, // 是否可编辑
        language: 'sql', // 语言类型
        theme: 'vs', // 编辑器主题
        lineNumbers: "on", // 行号 取值
        lineNumbersMinChars: 6
      },
      // 表单参数
      form: {},
      form2:{},
      formReduction:{},
      // 表单校验
      rules: {
        sqlScript: [
          {
            required: true,
            validator: equalToSqlScript,
            message: "SQL脚本不能为空",
            trigger: ["blur","change"]
          }
        ],
        version: [
          { required: true, message: "版本号不能为空", trigger: "change"}
        ],
        remark: [
          { required: true, message: "描述信息不能为空", trigger: "change"},
        ],
        layered: [ ]
      },
      rulesReduction: {
        reductionVersion:[{ required: true, message: '请选择要还原的版本号',trigger: 'blur'}]
      },
      // 表单校验
      rules2: {
        demandBugNum: [
          { required: true, message: "需求/者bug编号不能为空", trigger: "blur" }
        ],
        demandBugType: [
          { required: true, message: "需求/者bug不能为空", trigger: "change" }
        ],
        demandBugFsource: [
          { required: true, message: "外部/内部不能为空", trigger: "change" }
        ],
        version: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        demandBugDate: [
          { required: true, message: "需求BUG日期不能为空", trigger: "blur" }
        ] ,
        description: [
          { required: true, message: "需求内容不能为空", trigger: "blur" }
        ]
        ,
      }
    };
  },
  created() {
    this.init();
    this.getList();
  },
  methods: {
    // 内容改变自动获取值
    changeValue (val) {
      if(val && val.toUpperCase().includes("CREATE TABLE")){
        this.rules.layered = {
          required: true,
          message: "脚本包含建表语句，所在分层不能为空",
          trigger: ["change"]
        };
      }else{
        this.rules.layered = {
          required: false
        };
      }
    },
    /** 查询SQL脚本管理列表 */
    getList() {
      this.loading = true;
      listScript(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.scriptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    init(){
      init(this.queryParams).then(response => {
        this.modularTree=response.modularTree;
        this.customerTree=response.customerTree;
        this.reportTree=response.reportTree;
        this.demandBugInfoList=response.demandBugInfoList;
        this.versions=response.versions;
        this.reductionVersions=response.reductionVersions;
        // 系统参数控制
         this.getConfigKey("reportworld.script.coverPrimaryKey").then(response => {
           if(response.msg=='true'){
              this.coverPrimaryKeyDis = false;
           }else{
             this.coverPrimaryKeyDis = true;
          }
         });
    });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openMsg =false;
      this.openReduction=false;
      this.reset();
      this.queryParams.hisVersion="";
      this.init();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sqlScript: null,
        customerId: null,
        reportId: null,
        modularId: null,
        demandBugId: null,
        ftype: null,
        layered: null,
        fsource: null,
        dataBaseType: null,
        coverPrimaryKey: null,
        dataMark: null,
        followUpVersion:null,
        version: null,
        remark: null,
        status: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        approvalBy: null,
        approvalTime: null,
        hisVersion:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single=  false;
      this.multiple=  false;
      this.multipleProcess=  false;
      this.multipleRebut=  false
      // 选中数据的状态，来判断时候能点击
      this.checkstatus =selection.map(item => item.status);
      if(this.checkstatus.includes(1) || this.checkstatus.includes(2) || this.checkstatus.includes(4) || selection.length!==1){ // 修改的数据只能是待审核和审核退回的数据
        this.single=  true
      }
      if(this.checkstatus.includes(1) || this.checkstatus.includes(2) || this.checkstatus.includes(4) || !selection.length){ // 删除只能删除带审核和审核退回的按钮
        this.multiple=  true
      }
      if(!selection.length || this.checkstatus.includes(1) || this.checkstatus.includes(2) || this.checkstatus.includes(4) ||  this.checkstatus.includes(5)){ // 审核不通过的数据
        this.multipleProcess=  true
      }
      if(!selection.length || this.checkstatus.includes(1) || this.checkstatus.includes(2) || this.checkstatus.includes(4) ||  this.checkstatus.includes(5)){ //只有 待审核的数据才能 退回的按钮
         this.multipleRebut=  true
      }
      this.isShowUpdates =selection.map(item => item.isShowUpdate);
      if(this.isShowUpdates.includes(2)){ // 选择的不是自己的数据也不能修改和删除
        this.single=  true;
        this.multiple=  true
      }
    },
    // 更多操作触发
 /*   handleCommand(command, row) {
      switch (command) {
        case "processSqlScript":
          this.processSqlScript(row);
          break;
        case "rebutSqlScript":
          this.rebutSqlScript(row);
          break;
        default:
          break;
      }
    },*/
      /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
     },
    /** 新增按钮操作 */
    handleAdd() {
      this.opts.value= '';
      this.reset();
      this.open = true;
      this.title = "添加SQL脚本管理";
      this.isUpdate =true;
      this.form.coverPrimaryKey = parseInt(this.dict.type.sys_yes_no[1].value);
      this.form.dataMark= parseInt(this.dict.type.sys_yes_no[1].value);
      this.form.version = this.dict.type.report_version[0].value;
      this.queryParams.hisVersion=this.form.version;
      this.form.status = parseInt(this.dict.type.sys_common_status[0].value);
      this.disModular =false;
      this.disCustomer =false;
      this.disReport =false;
      this.init(); // 选择版本之后重新加载所属报表，模块，需求bug信息
    },
    handleViewLogger(row){
      this.msg = row.checkLogger;
      this.openMsg = true;
      this.titleMsg ="SQL脚本检查信息";
      this.subScriptSql=false;
    },
    /** 修改按钮操作 */
    handleUpdate(row,isUpdate) {
      this.reset();
      const id = row.id || this.ids
      getScript(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改SQL脚本管理";
        this.isUpdate =true;
        this.queryParams.hisVersion=response.data.version;
      if(isUpdate == false){
        this.title = "SQL脚本详情";
        this.isUpdate =false;
        this.queryParams.hisVersion='';
      }
        if(null !=response.data.reportId && "" != response.data.reportId){
          this.selectReport()
        }else{
          this.form.reportId = null;
        }
        if(null !=response.data.customerId && "" != response.data.customerId){
          this.selectCustomer()
        }else{
          this.form.customerId = null;
        }
        if(null != response.data.modularId && "" != response.data.modularId){
          this.selectModular()
        }else{
          this.form.modularId = null;
        }
        this.opts.value= '';
        this.opts.value= response.data.sqlScript;
        this.init(); // 选择版本之后重新加载所属报表，模块，需求bug信息
        this.followUpVersionShow=true;
        if(response.data.version == this.dict.type.report_version[0].value){
          this.followUpVersionShow=false;
        }
      });
    },
    /**
     * 所属客户，所属模块，所属报表，只能选中一个
     */
    selectModular(value){
      this.disCustomer =true;
      this.disReport =true;
      this.disModular =false;
    },
    selectCustomer(value){
      this.disModular =true;
      this.disReport =true;
      this.disCustomer =false;
      // 选择客户后同时存在默认是
      this.form.coverPrimaryKey = parseInt(this.dict.type.sys_yes_no[0].value);
    },
    selectReport(value){
      this.disModular =true;
      this.disCustomer =true;
      this.disReport =false;
    },
    clearSlect(){
      this.disModular =false;
      this.disCustomer =false;
      this.disReport =false;
      this.form.coverPrimaryKey = parseInt(this.dict.type.sys_yes_no[1].value);
      return true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          /*if(!this.form.modularId && !this.form.customerId && !this.form.reportId){
            this.$modal.msgError("所属模块，所属客户，所属报表，必须选择一个！");
            return;
          }*/
          this.form.sqlScript = this.$refs.monacoEditor.getVal();
          if ((this.form.sqlScript.toUpperCase().includes('CREATE TABLE') ||
              this.form.sqlScript.toUpperCase().includes('ALTER TABLE') ||
              this.form.sqlScript.toUpperCase().includes('DROP TABLE') ||
              this.form.sqlScript.toUpperCase().includes('COMMENT ON COLUMN'))
            && (this.form.sqlScript.toUpperCase().includes('INSERT INTO') ||
              (this.form.sqlScript.toUpperCase().includes('UPDATE') && this.form.sqlScript.toUpperCase().includes('SET')) ||
                this.form.sqlScript.toUpperCase().includes('DELETE FROM'))) {
            this.$modal.msgError("CREATE,ALTER,DROP,COMMENT语句需要和INSERT，UPDATE，DELETE脚本分开提交，请检查脚本信息！");
            return;
          }
          this.butloading=true;
          this.$modal.loading("正在检查SQL语句，请稍候...");
          checkSqlScript(this.form).then(response => {
            if(response.msgInfo){
              this.msg = response.msgInfo;
             }
            this.openMsg = true;
            this.titleMsg ="SQL脚本检查信息";
            if(response.result== false){
             this.subScriptSql=false;
             }else{
               this.subScriptSql=true;
          }
        }).finally(() => {this.$modal.closeLoading();this.butloading=false;});
        }
      });
    },
    submitSubScriptSql() {
      this.$refs["form"].validate(valid => {
        if (valid) {
           this.form.sqlScript = this.$refs.monacoEditor.getVal();
           this.form.checkLogger = this.msg;
           this.butloading=true;
            if (this.form.id != null) {
             updateScript(this.form).then(response => {
               this.$modal.msgSuccess("修改成功");
               this.open = false;
               this.openMsg = false;
               this.getList();
             }).finally(() => {
               this.$modal.closeLoading();
               this.butloading=false
               this.queryParams.hisVersion="";
               this.init();
             });
           } else {
             addScript(this.form).then(response => {
               this.$modal.msgSuccess("新增成功");
               this.open = false;
               this.openMsg = false;
                this.getList();
             }).finally(() => {
                this.butloading=false
                this.queryParams.hisVersion="";
                this.init();
             });
           }
        }
      });
    },
    reductionData(){  // 还原版本选择
      this.openReduction=true;
      this.titleReduction ="还原版本选择";
    },
    submitReduction(){ //还原版本
      const reductionVersion =this.formReduction.reductionVersion;
      this.$refs["formReduction"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认还原版本吗？').then(function() {
            return reductionData(reductionVersion);
          }).then(() => {
            this.getList();
          this.openReduction=false;
          this.$modal.msgSuccess("还原成功");
        }).catch(() => {});
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delScript(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 审核按钮操作 */
    processSqlScript(row) {
      const ids = row.id || this.ids;
      this.butloading=true;
      this.$modal.loading("正在审核SQL语句，请稍候...");
      this.$modal.confirm('是否确认审核脚本？').then(function() {
        return processSqlScript(ids);
      }).then(response => {
        if(response.msgInfo){
          this.msg = response.msgInfo;
        }
        this.titleMsg = "SQL脚本审核信息";
        this.openMsg = true;
        this.subScriptSql=false;
        this.getList();
        this.$modal.closeLoading();
        this.butloading=false
    }).finally(() => { this.$modal.closeLoading();this.butloading=false});
    },
    /** 退回按钮操作 */
    rebutSqlScript(row) {
      if(row.id){
        this.idList.push(row.id)
      }else{
        this.idList = this.ids;
      }
      this.$prompt('请输入退回脚本的原因', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning",
        inputPattern: /^.{5,200}$/,
        inputErrorMessage: "退回原因长度必须介于 5 和 200 之间"
      }).then(({ value }) => {
        rebutSqlScript(this.idList, value).then(response => {
        this.$modal.msgSuccess("退回成功");
      this.getList();
    });
    }).catch(() => {});
    },
    changeVersion(value){
      if(value == this.dict.type.report_version[0].value){
          this.followUpVersionShow=false;
      }else{
        this.followUpVersionShow=true;
        this.form.followUpVersion= parseInt(this.dict.type.sys_yes_no[1].value);
      }
      this.queryParams.hisVersion=value;
      this.init(); // 选择版本之后重新加载所属报表，模块，需求bug信息
      // 清除选择的所属报表，模块，客户信息
      this.$set(this.form, "modularId", null);
      this.$set(this.form, "customerId", null);
      this.$set(this.form, "reportId", null);
      this.$set(this.form, "demandBugId",null);
      this.disModular =false;
      this.disCustomer =false;
      this.disReport =false;
    },
    changeDemandBugInfo(value){
      this.form2 = {
        id: null,
        demandBugNum: null,
        demandBugType: null,
        demandBugFsource: null,
        version: null,
        status: null,
        demandBugDate: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        hisVersion:null,
      };
      if("-1" == value){
        this.$set(this.form, "demandBugId", null);
        this.openDemandbug =true;
        this.titleDemandbug = "添加需求BUG信息";
        this.form2.version = this.form.version;
        this.form2.status = parseInt(this.dict.type.sys_common_status[0].value);
        this.form2.demandBugType = parseInt(this.demandBugTypes[0].value);
        this.form2.demandBugFsource = parseInt(this.demandBugFsources[0].value);
        var date = new Date();
        this.form2.demandBugDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate());
      }
    },
    /** 提交按钮 */
    submitForm2() {
      this.$refs["form2"].validate(valid => {
        if (valid) {
          this.butloading=true;
          this.form2.hisVersion =this.queryParams.hisVersion;
          addInfo(this.form2).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.openDemandbug = false;
            this.init(); // 重新加载
            this.$set(this.form, "demandBugId", response.msg);
        }).finally(() => {this.butloading=false});
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.ids=JSON.stringify(this.ids);
      this.download('reportworld/script/export', {
        ...this.queryParams
      }, `script_${new Date().getTime()}.xlsx`)
    },
    handleExportSql(){
      this.queryParams.ids=JSON.stringify(this.ids);
      this.download('reportworld/script/exportSql', {
        ...this.queryParams
    }, `script_${new Date().getTime()}.sql`)
    },
    tableRowStyle({ row, rowIndex}){
        return getTableRowStyle(row,rowIndex,this.ids);
    },
    rowClick(row, column, event) { //单击行
      this.$refs.script.toggleRowSelection(row);
    }
  }
};
</script>
